package net.zoneland.geological.project.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import net.zoneland.geological.project.entity.Tbl_project;
import net.zoneland.geological.project.entity.Tbl_zht;
import net.zoneland.geological.project.service.Tbl_projectServiceI;
import net.zoneland.geological.project.service.Tbl_zhtServiceI;
import net.zoneland.geological.station.entity.Tbl_station_info;
import net.zoneland.geological.station.service.Tbl_station_infoServiceI;
import net.zoneland.geological.system.entity.Tbl_area;
import net.zoneland.geological.system.service.Tbl_areaServiceI;
import net.zoneland.geological.usermanage.entity.Tbl_user;
import net.zoneland.geological.usermanage.service.Tbl_user_datapermissionServiceI;
import net.zoneland.greenleaf.common.pagination.Pagination;
import net.zoneland.greenleaf.system.controller.BaseController;

/**
 * 灾害体信息操作控制层(Controller|Action)

 * 表   名：TBL_ZHTCONTROLLER<br/>
 * 注   释：灾害体信息<br/>
 * 作   者：李义<br/>
 * 日   期：2017-05-29 20:13:34
**/
@Controller
@RequestMapping("tbl_zht")
public class Tbl_zhtController extends BaseController { 

	/**
	 * 如果需要系统对此Controller的访问进行监控，记录服务访问的时间，耗时，那么请将monitor属性设置为“true”
	 */

	public boolean monitor = false; 

	private static Logger logger = Logger.getLogger(Tbl_zhtController.class);

	//获取类的名称
	@SuppressWarnings("unused")
	private String clazzName = new Object() {
		public String getClassName() {
			String clazzName = this.getClass().getName();
			return clazzName.substring(0, clazzName.lastIndexOf('$'));
		}
	}.getClassName();

	/**
	 * tbl_zhtService
	 * @param tbl_zhtService
	**/
	@Autowired
	private Tbl_zhtServiceI tbl_zhtService;
	@Autowired
	private Tbl_projectServiceI tbl_projectService;
	@Autowired
	private Tbl_areaServiceI tbl_areaService;
	@Autowired
	private Tbl_station_infoServiceI tbl_station_infoService;
	
	@Autowired
	private Tbl_user_datapermissionServiceI tbl_user_datapermissionService;
	/**
	 * 根据ID获取信息数据
	 * @param id
	 * @return
	**/
	@RequestMapping( method = RequestMethod.GET, value = "/{id}", produces = "text/html;charset=UTF-8" )
	@ResponseBody
	public Object get( @PathVariable("id") String id ){
		Map<String, Object> map = new HashMap<String, Object>();
		Tbl_zht entity = null;
		Boolean check = true;

		map.put("id", id);
		if( id == null || "(0)".equals( id ) || id.isEmpty() ){
			check = false;
			map.put("result", "error");
			map.put("message", "系统获取到的ID不正常，ID:" + id );
		}
		if( check ){
			try {
				entity = tbl_zhtService.get( map );
			} catch (Exception e) {
				check = false;
				map.put("result", "error");
				map.put("message", "系统根据ID获取对象失败!");
				logger.error("系统根据ID获取对象发生异常。ID:" + id, e);
			}
		}
		if( check ){
			if( entity != null ){
				map.put( "result", "success");
				map.put( "data", entity );
			}else{
				map.put( "result", "error");
				map.put( "message", "数据不存在！ID:" + id );
			}
		}
		return map;
	}

	/**
	 * 获取灾害体信息列表
	 * 返回JSON格式数据，如果不需要分页，您可以考虑将pagesize设置为足够大的数字，系统默认为20
	 * @param Map<String, Object> paramMap
	**/
	@RequestMapping( method = RequestMethod.POST, value = "/list" )
	@ResponseBody
	public Object list( @RequestBody Map<String, Object> paramMap ) {
		String page = "1";
		Integer pagesize = 20, totalRecord=0;
		List<Tbl_zht> list  = null;
		Map<String, Object> map=new HashMap<String,Object>();
		Pagination<?> pagination = null;
		Boolean check = true;
		List<String> visibleStationIds  = null;
		Tbl_user tbl_user = null;
		
		if( paramMap == null ){
			check = false;
			map.put( "result", "error");
			map.put( "message", "参数列表为空，无法进行数据查询!");
		}
		
		if( check ){	
			if( this.getSession().getAttribute( "login_user" ) != null ) {
				tbl_user = (Tbl_user)this.getSession().getAttribute( "login_user" );
			}else {
				check = false;
				map.put( "result", "error" );
				map.put( "login", false );
				map.put( "message", "用户未登录!" );
			}
		}
		
		if( check ){	
			//先查询用户可以访问到的所有设备ID列表
			try {
				visibleStationIds = tbl_user_datapermissionService.getZhtIdsWithPermission( tbl_user.getLogin_name() );
				if( visibleStationIds != null && !visibleStationIds.isEmpty() ) {
					paramMap.put( "ids", visibleStationIds );
				}else {
					paramMap.put( "ids", new String[] {"无"} );
				}
				map.clear();
			} catch (Exception e ) {
				check = false;
				map.put( "result", "error" );
				map.put( "message", "系统根据根据用户信息获取数据权限时发生异常!" );
				logger.error( e );
			}
		}
		
		if( check ){
			if( paramMap.get( "tree_level" ) != null ){
				if( "0".equals( paramMap.get( "tree_level" ).toString() )){
					//城市（深圳 - 440300）
				} else if( "1".equals( paramMap.get( "tree_level" ).toString() )){
					paramMap.put( "project_id", paramMap.get( "tree_id" ).toString() );
				}
			}			
		}
		if( check ){
			if( paramMap.get( "page" )!=null){
				page = paramMap.get( "page" ).toString();
			}
			if( paramMap.get( "pagesize") != null){
				try{
					pagesize = Integer.parseInt(paramMap.get( "pagesize" ).toString());
				}catch( Exception e ){
					pagesize = 20;
				}
			}
		}
		if( check ){
			try{
				totalRecord = tbl_zhtService.getListCount( paramMap );
			}catch( Exception e ){
				check = false;
				map.put( "result", "error");
				map.put( "message", "系统根据条件查询信息数据条目总数时发生异常!");
				logger.error( e );
			}
		}
		if( check ){
			try{
				pagination = Pagination.newPagination( pagesize, page, totalRecord );
				paramMap.put( "startRow", pagination.getStartRow() );
				paramMap.put( "pageSize", pagesize );
				/**
			 	* 如果需要按某列进行排序，可以再多给两个参数：orderColName, orderType
			 	* paramMap.put( "orderColName", "ID");
			 	* paramMap.put( "orderType", "DESC");
			 	**/
			}catch( Exception e ){
				check = false;
				map.put( "result", "error" );
				map.put( "message", "系统根据条件进行分页信息计算时发生异常！" );
				logger.error( e );
			}
		}
		if( check ){	
			if( totalRecord>0 ){
				try{
					list = tbl_zhtService.getList( paramMap );
				}catch( Exception e ){
					check = false;
					map.put( "result", "error" );
					map.put( "message", "系统根据条件进行信息列表查询信息数据时发生异常!" );
					logger.error( e );
				}
			}
		}
		if( check ){
			if( list == null ){
				list = new ArrayList<Tbl_zht>();
			}else{
				list = supplementEntityInfo( list );
			}
		}
		if( check ){
			map.put( "result", "success" );
			map.put( "message", "系统查询信息数据成功!" );
			map.put( "pagination", pagination );
			map.put( "data", list );
		}
		return map;
	}

	private List<Tbl_zht> supplementEntityInfo(List<Tbl_zht> list) {
		String projectAreaCn = "";
		Tbl_area tbl_area = null;
		Tbl_project tbl_project = null;
		Map<String, Object> paramMap = new HashMap<>();
		//补充显示时需要的项目地区，数据库里只存了编码
		for( Tbl_zht zht : list ){
			projectAreaCn = "";
			try {
				if( zht.getProject_id() != null && !zht.getProject_id().isEmpty() ){
					paramMap.clear();
					paramMap.put( "id" , zht.getProject_id() );
					tbl_project = tbl_projectService.get( paramMap );
					if( tbl_project != null ){
						zht.setProjectname( tbl_project.getName() );
					}
				}
				if( zht.getProvince_code() != null && zht.getProvince_code() != 0 ){
					paramMap.clear();
					paramMap.put( "area_code" , zht.getProvince_code() );
					tbl_area = tbl_areaService.getWithCode( paramMap );
					if( tbl_area != null ){
						projectAreaCn = projectAreaCn + tbl_area.getArea_name();
					}
				}
				if( zht.getCity_code() != null && zht.getCity_code() != 0 ){
					paramMap.clear();
					paramMap.put( "area_code" , zht.getCity_code() );
					tbl_area = tbl_areaService.getWithCode( paramMap );
					if( tbl_area != null ){
						projectAreaCn = projectAreaCn + "-" + tbl_area.getArea_name();
					}
				}
				if( zht.getArea_code() != null && zht.getArea_code() != 0 ){
					paramMap.clear();
					paramMap.put( "area_code" , zht.getArea_code() );
					tbl_area = tbl_areaService.getWithCode( paramMap );
					if( tbl_area != null ){
						projectAreaCn = projectAreaCn + "-" + tbl_area.getArea_name();
					}
				}
				zht.setAreaname( projectAreaCn );
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return list;
	}
	/**
	 * 增加或编辑一个灾害体信息信息
	 * 返回JSON格式数据
	 * @param entity
	**/
	@RequestMapping( method = RequestMethod.POST, value = "/save" )
	@ResponseBody
	public Object save( @RequestBody Map<String, Object> paramMap ){
		Map<String, Object> map = new HashMap<String, Object>();
		Tbl_zht entity = null;
		Boolean check = true;

		if( paramMap == null ){
			check = false;
			map.put( "result", "error");
			map.put( "message", "需要保存的信息数据为空!");
		} else {
			try {
				entity = (Tbl_zht)mapToObject( paramMap, Tbl_zht.class );
			} catch (Exception e) {
				check = false;
				map.put( "result", "error");
				map.put( "message", "将数据转换为对象时发生异常!");
				logger.error( "将数据转换为对象时发生异常!", e );
			}
		}
		if( check ){
			map = validate( entity, map );
			if( map.get( "result" ) == null || "error".equalsIgnoreCase( map.get( "result" ).toString() ) ){
				check = false;
			}
		}
		if( check ){
			try{
				entity = tbl_zhtService.addOrUpdate( entity );
				map.put( "result", "success");
				map.put( "message", "保存灾害体信息信息数据成功!");
				map.put( "data", entity );
			}catch( Exception e ){
				map.put( "result", "error" );
				map.put( "message", "保存灾害体信息信息数据失败!" );
				logger.error("保存灾害体信息信息数据失败!", e);
			}
		}
		return map;
	}

	/**
	 * 对需要进行保存的对象里的信息校验
	 * @param entity
	 * @param map 
	 * @return
	 */
	private Map<String, Object> validate( Tbl_zht entity, Map<String, Object> map ) {
		//TODO 这里进行所有的数据校验工作
		//查询所属项目信息
		Tbl_project tbl_project = null;
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put( "id" , entity.getProject_id() );
		try {
			tbl_project = tbl_projectService.get(paramMap);
			if( tbl_project != null ){
				entity.setArea_code( tbl_project.getArea_code() );
				entity.setCity_code( tbl_project.getCity_code() );
				entity.setProvince_code( tbl_project.getProvince_code() );
				entity.setProjectname( tbl_project.getName() );
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if( entity.getCreate_time() == null ){
			entity.setCreate_time( new Date() );
		}
		if( entity.getUpdate_time() == null ){
			entity.setUpdate_time( new Date() );
		}
		entity.setVersion( 1 );
		entity.setDeleted( 0 );
		
		map.put("result", "success");
		return map;
	}

	/**
	 * 根据ID删除一个灾害体信息信息
	 * 返回JSON格式数据
	 * @param int id
	**/
	@RequestMapping( method = RequestMethod.DELETE, value = "/{id}" )
	@ResponseBody
	public Object deleteById( @PathVariable( "id" ) String id ){
		Map<String, Object> map = new HashMap<String, Object>();
		Tbl_zht entity = null;
		Boolean check = true;

		map.put( "id", id );
		if( id == null || id.isEmpty() || "id".equalsIgnoreCase( id )){
			check = false;
			map.put( "result", "error" );
			map.put( "message", "需要删除的信息ID为空!" );
		}
		if( check ){
			try {
				entity = tbl_zhtService.get( map );
				if( entity == null ){
					check = false;
					map.put( "result", "error" );
					map.put( "message", "需要删除的信息数据不存在失败!ID:" + id );
				}
			} catch (Exception e) {
				check = false;
				map.put( "result", "error" );
				map.put( "message", "根据ID查询需要删除的信息数据失败!ID:" + id );
				logger.error( "根据ID查询需要删除的信息数据失败!ID:" + id, e);
			}
		}
		if( check ){
			try {
				tbl_zhtService.delete( map );
				map.put( "result", "success" );
				map.put( "message", "成功删除一个信息数据!" );
			} catch (Exception e) {
				check = false;				map.put( "result", "error");
				map.put( "message", "删除信息数据失败!ID:" + id );
				logger.error( "删除信息数据失败!ID:" + id, e);
			}
		}
		return map;
	}

	/**
	 * 根据ID删除多个灾害体信息信息
	 * 返回JSON格式数据
	 * @param Map<String, Object> paramMap
	**/
	@RequestMapping( method = RequestMethod.POST, value = "/delete/batch" )
	@ResponseBody
	public Object deleteByIds( @RequestBody Map<String, Object> paramMap ){
		Map<String, Object> map = new HashMap<String, Object>();
		String ids_str = null;
		Boolean check = true;

		if( paramMap == null || paramMap.get( "ids" ) == null ){
			check = false;
			map.put( "result", "error" );
			map.put( "message", "参数列表为空，无法进行数据删除!" );
		}
		if( check ){
			ids_str = (String)paramMap.get( "ids" );
			if( ids_str != null && ids_str.isEmpty() ){
				check = false;
				map.put( "result", "error" );
				map.put( "message", "参数列表中ID列表为空，无法进行数据删除!" );
			}else{
				map.put( "ids", ids_str.split( "," ) );
			}
		}
		if( check ){
			try {
				tbl_zhtService.delete( map );
				map.put( "result", "success" );
				map.put( "message", "成功删除信息数据!" );
			} catch (Exception e) {
				map.put( "result", "error" );
				map.put( "message", "删除信息数据失败!ID:" + paramMap.get( "ids" ) );
				logger.error( "系统信息数据失败!ID:" + paramMap.get( "ids" ), e );
			}
		}
		return map;
	}
	
	@RequestMapping("/all")
	@ResponseBody
	public Map<String, Object> getAll() throws Exception{
		Map<String, Object> map = new HashMap<>();
		
		List<Tbl_zht> zhtList = tbl_zhtService.getList(new HashMap<String,Object>());
		map.put("zhtList", zhtList);
		
		List<List<Tbl_station_info>> list = new ArrayList<>();
		for(Tbl_zht zht : zhtList) {
			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("zht_id", zht.getId());
			
			List<Tbl_station_info> stationList = tbl_station_infoService.getList(paramMap);
			list.add(stationList);
			
		}
		map.put("stationList", list);
		
		return map;
	}
}
